import { Button, Radio, Slider, message, Modal,Spin } from 'antd';
import * as React from 'react';
import { WeaLocaleProvider, WeaInputSearch, WeaBrowser, WeaDialog, WeaInput, WeaSelect, WeaHelpfulTip } from 'ecCom';
import D3Tree from '../../common/tree/RectTree';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Resizable } from 'react-resizable';
import './index.less';
import NodeForm from './NodeForm';
import CombineSetDialog from '../../dialog/combineSetDialog';
import TemplateBrowser from '../../dialog/templateBrowser';
import OperateMenuDialog from '../../dialog/operateMenuDialog';
import BeforeNodeOperateMenuDialog from '../../dialog/beforeNodeOperateMenuDialog';
import FiledPropDialog from '../../dialog/filedPropDialog';
import JoinCubeDialog from '../../dialog/joinCubeDialog';
import NodeModal from '../../dialog/NodeModal';
import DynamicNodePreviewDialog from '../../dialog/DynamicNodePreviewDialog';
const getLabel = WeaLocaleProvider.getLabel;


@inject('edcPathDesignerStore')
@observer
export default class PathDesigner extends React.Component {
    searchedNode = []
    componentDidMount() {
        const { edcPathDesignerStore: store, params, readonly } = this.props;
        store.initPath(params, readonly);
    }
    render() {
        const { edcPathDesignerStore: store } = this.props;
        const { nodeForm, readonly, hasChildren,path,versionNode } = store;
        const dataParams = path?{pathid:path.id,nodeid:nodeForm.id}:{};
        return (
            <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@1lee5i`} spinning={store.loading} size="large" wrapperClassName="wea-edc-excel-spin">
            <div className="wea-edc-path-designer">
                <div className="tree-layout-toggle d3-tree-toggle">
                    {!readonly && <Button.Group ecId={`${this && this.props && this.props.ecId || ''}_undefined@gtflwa`}>
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@s0yqch`} className="opt-btn" onClick={this.importPath}>{getLabel(502276, '导入路径')}</Button>
                        {versionNode &&<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@xqdltb`} className="opt-btn" onClick={this.saveAsTemplate} disabled={store.loading}>
                            <i className="icon-coms-Preservation" style={{ marginRight: 5 }} />
                            {getLabel('502642', '存为模板')}
                        </Button>}
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@x26vye`} className="opt-btn" onClick={this.setCombine}>
                            <i className="icon-coms-Flow-setting" style={{ marginRight: 5 }} />
                            {getLabel('502643', '汇总设置')}
                        </Button>
                        {versionNode && <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bk6h9q`} disabled={!nodeForm.isInit} onClick={this.saveNode} disabled={store.loading} className="opt-btn">{getLabel(30986, '保存')}</Button>}
                    </Button.Group>}
                    {!readonly && versionNode && <Button.Group ecId={`${this && this.props && this.props.ecId || ''}_undefined@jwsmsb`} className="linked">
                        {versionNode.children.length>0 && <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mqi146`} disabled={!nodeForm.isInit} onClick={this.addChildrenNode} className="opt-btn">{getLabel(502284, '添加下级')}</Button>}
                        {nodeForm.parentid != 0 && <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rbkdbd`} disabled={!nodeForm.isInit} onClick={this.deleteNode} className="opt-btn">{getLabel(502286, '删除')}</Button>}
                        {hasChildren && <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vuxbfx`} disabled={!nodeForm.isInit} onClick={this.deleteChildren} className="opt-btn">{getLabel(502285, '删除下级')}</Button>}
                    </Button.Group>}
                    {!readonly && versionNode && versionNode.children.length==0 && <Button.Group ecId={`${this && this.props && this.props.ecId || ''}_undefined@j17jph`}>
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@oe9szv`} disabled={!nodeForm.isInit} onClick={this.addChildren} className="opt-btn">{getLabel('505966', '选择人员')}</Button>
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ybpe2v`} disabled={!nodeForm.isInit} onClick={this.addDynamicChild} className="opt-btn">{getLabel('519955', '添加动态路径')}</Button>
                        </Button.Group>}
                    <Radio.Group ecId={`${this && this.props && this.props.ecId || ''}_undefined@rl3ic2`} value={store.layout} onChange={this.changeLayout}>
                        <Radio.Button ecId={`${this && this.props && this.props.ecId || ''}_undefined@a1docf`} value="0">{getLabel(502277, '左')}</Radio.Button>
                        <Radio.Button ecId={`${this && this.props && this.props.ecId || ''}_undefined@gzi9oa`} value="2">{getLabel(502278, '右')}</Radio.Button>
                        <Radio.Button ecId={`${this && this.props && this.props.ecId || ''}_undefined@k8hkkr`} value="1">{getLabel(502279, '上')}</Radio.Button>
                        <Radio.Button ecId={`${this && this.props && this.props.ecId || ''}_undefined@ngokpi`} value="3">{getLabel(502280, '下')}</Radio.Button>
                    </Radio.Group>
                    <div className="edc-zoom-line">
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@icjwzd`}
                            onClick={this.zoomOut}
                        >
                            <i className="anticon">
                                <svg viewBox="64 64 896 896" class="" data-icon="zoom-out" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M637 443H325c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h312c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8zm284 424L775 721c122.1-148.9 113.6-369.5-26-509-148-148.1-388.4-148.1-537 0-148.1 148.6-148.1 389 0 537 139.5 139.6 360.1 148.1 509 26l146 146c3.2 2.8 8.3 2.8 11 0l43-43c2.8-2.7 2.8-7.8 0-11zM696 696c-118.8 118.7-311.2 118.7-430 0-118.7-118.8-118.7-311.2 0-430 118.8-118.7 311.2-118.7 430 0 118.7 118.8 118.7 311.2 0 430z"></path></svg></i>
                        </Button>
                        <Slider ecId={`${this && this.props && this.props.ecId || ''}_Slider@4a5ovs`}
                            value={store.scale}
                            marks={{ 1: '10%', 20: '200%', [store.scale]: `${store.scale * 10}%` }}
                            min={1} max={20}
                            tipFormatter={value => `${value * 10}%`}
                            onChange={store.changeScale}
                        >
                        </Slider>
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@i7cokj`}
                            onClick={this.zoomIn}
                        >
                            <i className="anticon">
                                <svg viewBox="64 64 896 896" class="" data-icon="zoom-in" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M637 443H519V309c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v134H325c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h118v134c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V519h118c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8zm284 424L775 721c122.1-148.9 113.6-369.5-26-509-148-148.1-388.4-148.1-537 0-148.1 148.6-148.1 389 0 537 139.5 139.6 360.1 148.1 509 26l146 146c3.2 2.8 8.3 2.8 11 0l43-43c2.8-2.7 2.8-7.8 0-11zM696 696c-118.8 118.7-311.2 118.7-430 0-118.7-118.8-118.7-311.2 0-430 118.8-118.7 311.2-118.7 430 0 118.7 118.8 118.7 311.2 0 430z"></path></svg>
                            </i>
                        </Button>
                    </div>
                    <Button.Group ecId={`${this && this.props && this.props.ecId || ''}_undefined@qdptsw`}>
                        <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@kf7l45`}
                            placeholder={getLabel('502644', '搜索节点')}
                            onSearch={this.searchNode}
                            onChange={this.changeSearchValue}
                        />
                    </Button.Group>
                    <Button.Group ecId={`${this && this.props && this.props.ecId || ''}_undefined@9kbhsg`}>
                        <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@rnjr08`}
                            className='edc-path-tips'
                            //style={{width:'226px'}}
                            value={getLabel('519344', 'Tips:有且仅有根节点时可修改路径类型')}
                            title={getLabel('519344', 'Tips:有且仅有根节点时可修改路径类型')}
                            disabled
                        />
                    </Button.Group>
                </div >
                {/* {
                    store.pathType === 1 ?
                        <D3Tree
                            data={toJS(store.versionNode)}
                            onClick={store.openNode}
                            showRight={store.showRight}
                            renderRight={<NodeForm store={store} />}
                            layout={store.layout}
                            style={{ height: 'calc(100% - 32px)', top: 50 }}
                            scale={store.scale}
                            zoom={this.zoom}
                            ref={ref => store.d3Tree  = ref}
                            showMenu={true}
                            onDelete={(readonly || !nodeForm.parentid) || this.deleteNode}
                            onAddChild={readonly || this.addChildren}

                            onAddDynamicChild={readonly || this.addDynamicChild}

                            onDeleteChild={(readonly) || (hasChildren && this.deleteChildren)}
                            onSynchro={readonly || this.synchronize}
                            showname={this.getShowname}
                            desc="hreflinkName"
                        ></D3Tree> : store.pathType === 2 ? <DynamicPathTree store={store}></DynamicPathTree> : null
                } */}
                {
                    <D3Tree ecId={`${this && this.props && this.props.ecId || ''}_D3Tree@elc6ah`}
                            data={toJS(store.versionNode)}
                            onClick={store.openNode}
                            showRight={store.showRight}
                            renderRight={<NodeForm ecId={`${this && this.props && this.props.ecId || ''}_NodeForm@sfz48b`} store={store} />}
                            layout={store.layout}
                            style={{ height: 'calc(100% - 32px)', top: 50 }}
                            scale={store.scale}
                            zoom={this.zoom}
                            ref={ref => store.d3Tree  = ref}
                            showMenu={true}
                            onDelete={(readonly || !nodeForm.parentid) || this.deleteNode}
                            pathType = {store.pathType}
                            onAddChild={readonly || this.addChildren}
                            onAddDynamicChild={readonly || this.addDynamicChild}
                            onDeleteChild={(readonly) || (hasChildren && this.deleteChildren)}
                            onSynchro={readonly || this.synchronize}
                            onPreview={readonly || this.onPreview}
                            showname={this.getShowname}
                            desc="hreflinkName"
                        ></D3Tree>
                }
                <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@ofqjat`}
                    ref={ref => this.browser = ref}
                    isSingle={false}
                    type={17}
                    customized={true}
                    onChange={this.addNodes}
                    icon="icon-coms02-Data-center"
                    iconBgcolor="#1a57a0"
                    title={getLabel(502284,'添加下级')}
                    memorise={true}
                    replaceDatas={store.childOpreator.slice()}
                    value={store.childOpreator.map(d => d.id).join(',')}
                />
                <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@7ib71a`} 
                    icon={"icon-coms02-Data-center"}
                    title={getLabel('510980','选择节点')}
                    type='edcAppPathNode' 
                    isSingle={false}
                    customized={true}
                    //memorise={true}
                    ref={ref => this.nodeBrowser = ref} 
                    dataParams={dataParams}
                    completeParams={dataParams}
                    destDataParams={dataParams}
                    onChange={store.synchronizeNode}
                />
                <CombineSetDialog ecId={`${this && this.props && this.props.ecId || ''}_CombineSetDialog@ocdnuw`} store={store.combineSetDialogStore} />
                <TemplateBrowser ecId={`${this && this.props && this.props.ecId || ''}_TemplateBrowser@u3pubp`} store={store.templateBrowserStore} onChange={store.loadTemplate}></TemplateBrowser>
                <OperateMenuDialog ecId={`${this && this.props && this.props.ecId || ''}_OperateMenuDialog@zzkm63`} store={store.operateMenuDialogStore}/>
                <BeforeNodeOperateMenuDialog ecId={`${this && this.props && this.props.ecId || ''}_BeforeNodeOperateMenuDialog@83vi88`} store={store.beforeNodeOperateDialogStore}/>
                <FiledPropDialog ecId={`${this && this.props && this.props.ecId || ''}_FiledPropDialog@n268x3`} store={store.fieldPropDialogStore}/>
                <JoinCubeDialog ecId={`${this && this.props && this.props.ecId || ''}_JoinCubeDialog@v6u9eh`} store={store.joinCubeDialogStore}/>
                <NodeModal ecId={`${this && this.props && this.props.ecId || ''}_NodeModal@fka58v`} store={store.nodeModalStore}/>
                <DynamicNodePreviewDialog ecId={`${this && this.props && this.props.ecId || ''}_DynamicNodePreviewDialog@zipg1z`} store={store.dynamicNodePreviewDialogStore}/>
            </div >
            </Spin>
        )
    }
    getShowname = (d) => {
        return `${d.name}`;
    }
    changeSearchValue = () => {
        this.searchedNode = [];
    }
    searchNode = (value) => {
        const { edcPathDesignerStore: store, params } = this.props;
        if (!value) {
            this.searchedNode = [];
            return;
        }
        if (store.d3Tree ) {
            if (this.searchedNode.length === 0) {
                this.timer = 0;
                this.searchedNode = store.d3Tree .searchNode(value.toLowerCase());
            }
            const length = this.searchedNode.length;
            if (length > 0) {
                store.d3Tree .centerNode(this.searchedNode[this.timer % length]);
                this.timer++;
            }
        }
    }
    zoom = (scale) => {
        const { edcPathDesignerStore: store, params } = this.props;
        store.changeScale(parseInt(scale * 10));
    }
    zoomIn = () => {
        const { edcPathDesignerStore: store, params } = this.props;
        store.changeScale(Math.min(store.scale + 1, 30));
    }
    zoomOut = () => {
        const { edcPathDesignerStore: store, params } = this.props;
        store.changeScale(Math.max(store.scale - 1, 1));
    }
    importPath = () => {
        const { edcPathDesignerStore: store, params } = this.props;
        store.openPathTemplateDialog();
    }
    setCombine = () => {
        const { edcPathDesignerStore: store, params } = this.props;
        store.combineSetDialogStore.open({ appid: params.appid });
    }
    changeLayout = (e) => {
        const { edcPathDesignerStore: store } = this.props;
        this.searchedNode = [];
        store.changeLayout(e.target.value);
    }

    saveNode = () => {
        const { edcPathDesignerStore: store } = this.props;
        store.saveNode();
    }
    saveAsTemplate = () => {
        const { edcPathDesignerStore: store } = this.props;
        if (store.d3Tree) {
            const { edcPathDesignerStore: store } = this.props;
            const svg = store.d3Tree .baseSvg;
            const g = store.d3Tree .svgGroup;
            const serializer = new XMLSerializer();
            let source = serializer.serializeToString(svg.node());
            source = '<?xml version="1.0" standalone="no"?>\r\n' + source;
            const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(source);
            const canvas = document.createElement("canvas");
            const { width, height } = svg.node().getBoundingClientRect();
            canvas.width = width;
            canvas.height = height;
            const context = canvas.getContext("2d");
            const image = new Image;
            image.src = url;
            image.onload = () => {
                context.drawImage(image, 50, 25);
                const img = canvas.toDataURL("image/png");
                store.saveAsTemplate(img);
            }
        }
    }
    onPreview = () => {
        const { edcPathDesignerStore: store } = this.props;
        const { nodeForm } = store;
        store.dynamicNodePreviewDialogStore.open(nodeForm.id);
    }
    addChildrenNode = () => {
        const { edcPathDesignerStore: store } = this.props;
        const pathType = store.pathType;
        if(pathType<3){
            this.addChildren();
        }else if(pathType==3){
            this.addDynamicChild();
        }
    }
    addDynamicChild = () => {
        const { edcPathDesignerStore: store } = this.props;
        const { nodeForm } = store;
        store.nodeModalStore.init(nodeForm);
        store.nodeModalStore.title=getLabel(502284,'添加下级');
        store.nodeModalStore.open();
    }
    addChildren = () => {
        const { edcPathDesignerStore: store } = this.props;
        const { nodeForm } = store;
        store.setChildOpreator([]);
        store.allChildOpreator(nodeForm.id).then((childOpreator) => {
            store.setChildOpreator(childOpreator);
            if (this.browser) {
                this.browser.openModal();
                const selectPerson = (ids, names, objs) => {
                    if (objs.length > 99) {
                        message.warn(getLabel('502645', '下级节点不能超过99个'));
                        this.browser.openModal();
                        return;
                    }
                    const { edcPathDesignerStore: store } = this.props;
                    const oldids = childOpreator.map(d => d.id);
                    const newids = objs.filter(d => oldids.indexOf(d.id) === -1).map(d => d.id);
                    if (newids.length === 0) {
                        message.warn(getLabel('502646', '请选择需要添加的人员'));
                        return;
                    }
                    store.addNodes(nodeForm.id, newids.join(','));
                }
                this.selectPerson = selectPerson;
            }
        });
    }
    addNodes = (ids, names, objs) => {
        this.selectPerson(ids, names, objs);
    }

    deleteNode = () => {
        Modal.confirm({
            title: getLabel('505951','删除节点') ,
            content: getLabel('505952','确认要删除选中的节点？') ,
            onOk: () => {
                const { edcPathDesignerStore: store } = this.props;
                const { nodeForm } = store;
                store.deleteNode(nodeForm.id);
            }
        });
    }

    deleteChildren = () => {
        Modal.confirm({
            title: getLabel('505953','删除节点') ,
            content: getLabel('505954','确认要删除所有下级节点？') ,
            onOk: () => {
                const { edcPathDesignerStore: store } = this.props;
                const { nodeForm } = store;
                store.deleteChildren(nodeForm.id);
            }
        });
    }

    synchronize = () => {
        if (this.nodeBrowser) {
            this.nodeBrowser.openModal();
        }
    }
}